<?php

namespace app\api\controller\user;

use app\admin\model\dts\activity\Notes;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\Db;
use OSS\OssClient;
/**
 * 家长端接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['upload'];
    protected $noNeedRight = ['*'];

    public function upload() {
        $attachment = null;
        
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

        //检测删除文件或附件
        $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
            //如果设定为不备份则删除文件和记录 或 强制删除
            if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
                if ($upload) {
                    //文件绝对路径
                    $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
                    @unlink($filePath);
                }
            }
        };

        //文件绝对路径
        $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
        try {
            $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
            //成功不做任何操作
        } catch (\Exception $e) {
            $checkDeleteFile($attachment, $upload, true);
            \think\Log::write($e->getMessage());
            $this->error("上传失败(1002)");
        }
        $checkDeleteFile($attachment, $upload);

        // 记录云存储记录
        $data = $attachment->toArray();
        \app\common\model\Attachment::where('id', $data['id'])->update(['storage' => 'alioss']);

        $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }

    //通知信息
    public function gardenNotice() {

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $title = $this->request->get('title');

        $user = $this->auth->getUserinfo();
        
        $service = new \app\api\controller\Service;
        $list = $service->gardenNotice($user, 0, 0, $title, $page, $pagesize);

        $this->success('success', $list);
    }
    

    //通知详情
    public function gardenNoticeInfo() {

        $id = $this->request->get('id');

        $user = $this->auth->getUserinfo();
        
        $service = new \app\api\controller\Service;
        $list = $service->gardenNoticeInfo($user, 0, $id);

        $this->success('success', $list);
    }

    //班级活动
    public function classesActivity() {
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $user = $this->auth->getUserinfo();

        $service = new \app\api\controller\Service;
        $list = $service->classesActivity($user, 0, false, 0, 0, null, null, $page, $pagesize);

        $this->success('success', $list);
    }

    //活动小记
    public function activityNotes() {

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $type = $this->request->get('type', 0);
        $realmId = $this->request->get('realmId');
        $labelId = $this->request->get('labelId');

        $user = $this->auth->getUserinfo();
        
        $query1 = ['dan.category' => Notes::category_2]; $query2 = []; $query2Raw = '';
        if(!$type) {
            $size = count($user['student']);
            foreach($user['student'] as $index => $item) {
                $temp = 'FIND_IN_SET('.$item['id'].',dan.student_ids) > 0';
                if($size - 1 > $index) {
                    $temp = $temp . ' OR ';
                }

                $query2Raw = $query2Raw . ' ' . $temp;
            }
        }else {
            $query2 = ['dan.create_id' => $user['id']];
        }
        $query3 = $realmId ? ['dan.dts_activity_realm_id' => $realmId] : [];
        $query4 = $labelId ? ['dan.dts_activity_label_id' => $labelId] : [];
        $query2Raw = $query2Raw ? $query2Raw : '1=1';

        $list = Db::name('dts_activity_notes')->alias('dan')
        ->field('dan.id,dan.category,dan.observe_goal,FROM_UNIXTIME(dan.createtime,"%Y-%m-%d %H:%i") as createtime,GROUP_CONCAT(stu.avatar) as avatars,GROUP_CONCAT(stu.username) as usernames,ad.nickname,dar.name as darname,dal.name as dalname')
        ->join([
            ['admin ad', 'ad.id = dan.admin_id', 'left'],
            ['dts_student stu', 'FIND_IN_SET(stu.id,dan.student_ids)', 'left'],
            ['dts_classes dc', 'dc.id = dan.classes_id', 'left'],
            ['dts_activity_realm dar', 'dar.id = dan.dts_activity_realm_id', 'left'],
            ['dts_activity_label dal', 'dal.id = dan.dts_activity_label_id', 'left'],
        ])
        ->where(array_merge($query1, $query2, $query3, $query4))
        ->whereRaw($query2Raw)
        ->order('dan.createtime', 'desc')
        ->group('dan.id')
        ->paginate($pagesize, false, ['page' => $page]);
        
        $this->success('success', $list);
    }

    //活动详情
    public function activityNotesInfo() {

        $notesId = $this->request->get('notesId', 0);

        $service = new \app\api\controller\Service;
        $info = $service->activityNotesInfo($notesId, 0);

        $this->success('success', $info);
    }

    //发布或编辑活动小记
    public function releaseActivityNotes() {

        $notesId = $this->request->post('notesId');
        $studentIds = $this->request->post('studentIds');
        $phenomenon = $this->request->post('phenomenon');
        $phenomenon_json = $this->request->post('phenomenon_json');
        $observe_goal = $this->request->post('observe_goal');

        if(!$studentIds || !$phenomenon || !$observe_goal) {
            $this->error('请填写活动小记内容');
        }

        $student = Db::name('dts_student')->where('id', $studentIds)->find();
        if(!$student) {
            $this->error('未找到学生信息');
        }

        $user = $this->auth->getUserinfo();
        $data = [
            'classes_id' => $student['classes_id'], 'student_ids' => $studentIds, 'phenomenon' => $phenomenon, 'phenomenon_json' => html_entity_decode($phenomenon_json),
            'observe_time' => date('Y-m-d H:i:s', time()), 'observe_goal' => $observe_goal, 'createtime' => time()
        ];

        if($notesId) {
            \app\admin\model\dts\activity\Notes::where('id', $notesId)->update($data);
        }else {
            $data['category'] = Notes::category_2;
            $data['create_id'] = $user['id'];
            \app\admin\model\dts\activity\Notes::create($data);
        }

        $this->success('success');
    }

    //删除活动小记
    public function delActivityNotes() {
        $notesId = $this->request->post('notesId');

        $notesModel = new \app\admin\model\dts\activity\Notes;
        $notesModel->where('id', $notesId)->delete();

        $this->success('success');
    }
}